package com.jf.blog_jf04.utils.interceptor;

import com.jf.blog_jf04.bean.Userinfo;
import com.jf.blog_jf04.service.UserinfoService;
import com.jf.blog_jf04.utils.MyConstants;
import com.jf.blog_jf04.utils.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserinfoService userinfoService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*获取token*/
        String token = request.getHeader(MyConstants.TOKEN_NAME);
        if (!StringUtils.hasText(token)) {
            throw new BusinessException(401, "未携带token");
        }
        /*验证token*/
        String loginId = redisTemplate.opsForValue().get(MyConstants.TOKEN_KEY + token);
        if (!StringUtils.hasText(loginId)) {
            throw new BusinessException(401, "token失效");
        }
        int id = Integer.parseInt(loginId);
        Userinfo userinfo = userinfoService.getById(id);
        if (userinfo == null) {
            throw new BusinessException(401, "token异常");
        }
        return true;
    }
}
